package com.sjgtw.cloud.web.freeze.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sjgtw.cloud.common.core.constant.CacheConstants;
import com.sjgtw.cloud.common.core.utils.DateUtils;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.service.SystemServerService;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.web.freeze.domain.FreezeRecord;
import com.sjgtw.cloud.web.freeze.mapper.FreezeFallbackMapper;
import com.sjgtw.cloud.web.freeze.mapper.FreezeRecordMapper;
import com.sjgtw.cloud.web.freeze.mapper.FreezeRestoreMapper;
import com.sjgtw.cloud.web.freeze.service.IFreezeRecordService;
import com.sjgtw.cloud.web.freeze.vo.ExportFreezeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 冻害记录Service业务层处理
 * 
 * @author lvyoufang
 * @date 2024-03-17
 */
@Service
public class FreezeRecordServiceImpl implements IFreezeRecordService 
{
    @Autowired
    private FreezeRecordMapper freezeRecordMapper;
    @Autowired
    private FreezeRestoreMapper restoreMapper;
    @Autowired
    private FreezeFallbackMapper fallbackMapper;
    @Autowired
    private SystemServerService systemServerService;
    @Autowired
    private FreezeFallbackMapper freezeFallbackMapper;
    @Autowired
    private FreezeRestoreMapper freezeRestoreMapper;
    @Autowired
    private RedisService redisService;

    /**
     * 查询冻害记录
     * 
     * @param id 冻害记录主键
     * @return 冻害记录
     */
    @Override
    public FreezeRecord selectFreezeRecordById(Long id)
    {
        return freezeRecordMapper.selectFreezeRecordById(id);
    }

    /**
     * 查询冻害记录列表
     * 
     * @param freezeRecord 冻害记录
     * @return 冻害记录
     */
    @Override
    public List<FreezeRecord> selectFreezeRecordList(FreezeRecord freezeRecord)
    {
        return freezeRecordMapper.selectFreezeRecordList(freezeRecord);
    }

    /**
     * 新增冻害记录
     * 
     * @param freezeRecord 冻害记录
     * @return 结果
     */
    @Override
    public int insertFreezeRecord(FreezeRecord freezeRecord)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        if (user != null) {
            freezeRecord.setCreateUserId(user.getUserid());
            freezeRecord.setCreateBy(user.getUsername());
        }
        freezeRecord.setCreateTime(DateUtils.getNowDate());
        dealFreezeType(freezeRecord);
        return freezeRecordMapper.insertFreezeRecord(freezeRecord);
    }

    public void dealFreezeType(FreezeRecord freezeRecord) {
        boolean greaterOrEqual10 = isAnyHeightGreaterOrEqual10(freezeRecord.getHeigthLeft(), freezeRecord.getHeigthRight());
        if (greaterOrEqual10) {
            freezeRecord.setFreezeType("10mm以上");
        } else {
            freezeRecord.setFreezeType("10mm以下");
        }
    }

    public static boolean isAnyHeightGreaterOrEqual10(String heightLeft, String heightRight) {
        // 检查heightLeft是否有效
        boolean leftIsValid = isValidNumber(heightLeft);
        // 检查heightRight是否有效
        boolean rightIsValid = isValidNumber(heightRight);

        if (leftIsValid && rightIsValid) {
            // 如果两个值都有效，进行比较
            return Integer.parseInt(heightLeft) >= 10 || Integer.parseInt(heightRight) >= 10;
        } else if (leftIsValid) {
            // 如果只heightLeft有效
            return Integer.parseInt(heightLeft) >= 10;
        } else if (rightIsValid) {
            // 如果只heightRight有效
            return Integer.parseInt(heightRight) >= 10;
        }

        // 如果两个值都无效
        return false;
    }

    /**
     * 判断字符串是否是有效数字
     *
     * @param str 要判断的字符串
     * @return 如果字符串是有效数字，则返回true；否则返回false
     */
    private static boolean isValidNumber(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 修改冻害记录
     * 
     * @param freezeRecord 冻害记录
     * @return 结果
     */
    @Override
    public int updateFreezeRecord(FreezeRecord freezeRecord)
    {

        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        freezeRecord.setUpdateBy(user.getUsername());
        freezeRecord.setUpdateTime(DateUtils.getNowDate());
        dealFreezeType(freezeRecord);
        return freezeRecordMapper.updateFreezeRecord(freezeRecord);
    }

    /**
     * 批量删除冻害记录
     * 
     * @param ids 需要删除的冻害记录主键
     * @return 结果
     */
    @Override
    public int deleteFreezeRecordByIds(String[] ids)
    {
        restoreMapper.deleteByFreezeIds(ids);
        fallbackMapper.deleteByFreezeIds(ids);
        return freezeRecordMapper.deleteFreezeRecordByIds(ids);
    }

    /**
     * 删除冻害记录信息
     * 
     * @param id 冻害记录主键
     * @return 结果
     */
    @Override
    public int deleteFreezeRecordById(Long id)
    {
        return freezeRecordMapper.deleteFreezeRecordById(id);
    }

    @Override
    public int deleteAllRecord(Long freezeId) {
        freezeFallbackMapper.deleteByFreezeId(freezeId);
        freezeRestoreMapper.deleteByFreezeId(freezeId);
        freezeRecordMapper.deleteFreezeRecordById(freezeId);
        return 1;
    }

    @Override
    public List<ExportFreezeVO> listExportData(FreezeRecord freezeRecord) {
        return freezeRecordMapper.listExportData(freezeRecord);
    }

    @Override
    public List<String> check(List<ExportFreezeVO> vos) {
        List<String> errors = new ArrayList<>();
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        List<String> deptNames = extractAndDeduplicateNames(vos);
        AjaxResult result = systemServerService.getDeptByNames(StringUtils.join(deptNames, ","));
        Map<String, Long> deptMap1 = new HashMap<>();
        Map<String, Long> deptMap2 = new HashMap<>();
        if (result != null) {
            Object object = result.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        deptMap1.put(json.getString("deptName"), json.getLong("deptId"));
                        deptMap2.put(json.getString("deptName"), json.getLong("parentId"));
                    }
                }
            }
        }

        for (ExportFreezeVO entity : vos) {
            if (StringUtils.isEmpty(entity.getWorkAreaName())) {
                errors.add(entity.getFreezeType() + "序号为" + entity.getNum() + "行数数据工区不能为空");
                continue;
            }
            if (deptMap1.containsKey(entity.getWorkAreaName())) {
                entity.setWorkArea(deptMap1.get(entity.getWorkAreaName()));
                entity.setSection(deptMap2.get(entity.getWorkAreaName()));
            } else {
                errors.add(entity.getFreezeType() + "序号为" + entity.getNum() + "行数据工区不存在");
            }
            if (user != null) {
                entity.setCreateBy(user.getUsername());
            }
            entity.setCreateTime(DateUtils.getNowDate());
        }
        return errors;
    }

    private static List<String> extractAndDeduplicateNames(List<ExportFreezeVO> entities) {
        Set<String> uniqueNamesSet = new HashSet<>();

        for (ExportFreezeVO entity : entities) {
            uniqueNamesSet.add(entity.getWorkAreaName());
        }

        return new ArrayList<>(uniqueNamesSet);
    }

}
